<?php

class MessagesController extends FrontEndController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view', 'getdialog', 'deletedialog', 'deletemessage', 'addmessage', 'checkmessage', 'getmessagelist', 'createmessage', 'checkdialog'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	public function actionIndex()
	{

		$dialogs=Messages::getDialogs();

		$this->render('index',array(
			'dialogs'=>$dialogs,
		));	
	}
	
	public function actionAddMessage(){
		if (Yii::app()->request->isAjaxRequest) {
			$data = array();
		
			if(isset($_POST['text'])){
				$data['text'] = $_POST['text'];
			}else{
				$data['text'] = '';
			}
			 
			if(isset($_POST['companion'])){
				$companion = $_POST['companion'];
			}else{
				$companion = 0;
			}
		
			if(isset($_POST['images'])){
				$images = explode(",", $_POST['images']);
			}else{
				$images = 0;
			}
		
			if(isset($_POST['videos'])){
				$videos = explode(",", $_POST['videos']);
			}else{
				$videos = 0;
			}
			 
			if(isset($_POST['musics'])){
				$musics = explode(",", $_POST['musics']);
			}else{
				$musics = 0;
			}
	
			$make = new Messages;
			$make->text = $data['text'];
			$make->to = $companion;
			$make->from = Yii::app()->user->id;
			$make->read = 0;
			$make->status_to = 1;
			$make->status_from = 1;
			$make->crdate = date("Y-m-d H:i:s");
	
			$make->save();
	
			$data['message_id'] =  $make->getPrimaryKey();
	
			$data['images'] = array();
	
			if($images){
				foreach($images as $image_id){
					if($image_id){
						$make = new MessagesPhotos;
						$make->message_id = $data['message_id'];
						$make->photo_id = $image_id;
	
						$make->save();
	
						$data['images'][] = Photos::model()->findByPk($image_id);
					}
				}
			}
	
			$data['videos'] = array();
	
			if($videos){
				foreach($videos as $video_id){
					if($video_id){
						$make = new MessagesVideos;
						$make->message_id = $data['message_id'];
						$make->video_id = $video_id;
	
						$make->save();
	
						$data['videos'][] = Video::model()->findByPk($video_id);
					}
				}
			}
	
			$data['musics'] = array();
	
			if($musics){
				foreach($musics as $music_id){
					if($music_id){
						$make = new MessagesMusics;
						$make->message_id = $data['message_id'];
						$make->music_user_id = $music_id;
						 
						$make->save();
	
						$data['musics'][] = MusicUser::model()->findByPk($music_id);
					}
				}
			}
	
			$user_info = Users::model()->findByPk(Yii::app()->user->id);
	
			$data['user'] = array(
				'name' => $user_info->full_name,
				'avatar' => $user_info->avatar
			);

			$email_to = Users::model()->findByPk( $companion, array('select' => 'full_name, email, massange_notification, last_visit') );
			if( ($email_to->massange_notification == 1) && ($email_to->last_visit < date("Y-m-d H:i:s", time() - 15*60)) ) 
			{
				Yii::app()->getModule('email');
				$email = new Email;
				$email->from = $user_info->email;
				$email->layout = 'common';
				$email->type = 'text/html';
				$email->to = $email_to->email;
				$email->view = 'main';
				$email->send(array('header' => 'Новое сообщение',
					'content' => $email_to->full_name . ', вы получили новое сообещение от '
						. $user_info->full_name . '<br>'
						. $data['text'] . '<br>'
						. 'Получено ' . Yii::app()->dateFormatter->formatDateTime(date("Y-m-d H:i:s"), 'long','short')
				));
			}
	
			$this->renderPartial('_newMessage',array(
				'message'=>$data
			));
		}else{
			$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
		}		
	}
	
	public function actionGetDialog(){
		Messages::model()->updateAll(array('read' => 1), '`from`=' . $_GET['companion'] . ' AND `to`= ' . Yii::app()->user->id . ' AND `read` = 0');
		
		$messages = Messages::model()->findAll(array(
			'order'=> 'crdate ASC',
			'condition'=>'(`from`=:user_1 AND `to`=:user_2 AND `status_to` = 1) OR (`from`=:user_2 AND `to`=:user_1 AND `status_from` = 1)',
			'params'=>array(':user_1'=>$_GET['companion'], ':user_2'=>Yii::app()->user->id)
		));	

		$companion = Users::model()->findByPk($_GET['companion']);
		$user = Users::model()->findByPk(Yii::app()->user->id);
		
		$this->render('messages', array(
			'messages'  => $messages,
			'companion' => $companion,
			'user' 		=> $user
		));				
	}
	
	public function actionDeleteDialog(){
		if (Yii::app()->request->isAjaxRequest) {
			if(isset($_GET['companion'])){
				Messages::model()->updateAll(array('status_to'   => 0),	'`from`=' . $_GET['companion'] . ' AND `to`  = ' . Yii::app()->user->id . '');
				Messages::model()->updateAll(array('status_from' => 0), '`to`  =' . $_GET['companion'] . ' AND `from`= ' . Yii::app()->user->id . '');
			}
		}else{
			$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
		}		
	}
	
	public function actionDeleteMessage(){
		if (Yii::app()->request->isAjaxRequest) {
			if(isset($_GET['message_id'])){
				Messages::model()->updateAll(array('status_to'   => 0),	'`to`  = ' . Yii::app()->user->id . ' AND id = ' . $_GET['message_id'] . '');
				Messages::model()->updateAll(array('status_from' => 0), '`from`= ' . Yii::app()->user->id . ' AND id = ' . $_GET['message_id'] . '');
			}
		}else{
			$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
		}
	}	

	public function actionCheckMessage(){
		if (Yii::app()->request->isAjaxRequest) {
			$messages = Messages::model()->findAll(array(
				'condition'=>'`to`=:user AND `status_to` = 1 AND `read` = 0',
				'params'=>array(':user'=>Yii::app()->user->id)
			));

			echo CJSON::encode(count($messages));
		}else{
			$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
		}		
	}
	
	public function actionCheckDialog(){
		if (Yii::app()->request->isAjaxRequest) {
			$dialogs = Messages::checkDialogs();
	
			echo CJSON::encode(count($dialogs));
		}else{
			$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
		}			
	}

	public function actionGetMessageList(){
		if (Yii::app()->request->isAjaxRequest) {
			Messages::model()->updateAll(array('read' => 1), '`from`=' . $_GET['companion'] . ' AND `to`= ' . Yii::app()->user->id . ' AND `read` = 0');			
			
			$messages = Messages::model()->findAll(array(
				'order'=> 'crdate ASC',
				'condition'=>'(`from`=:user_1 AND `to`=:user_2 AND `status_to` = 1) OR (`from`=:user_2 AND `to`=:user_1 AND `status_from` = 1)',
				'params'=>array(':user_1'=>$_GET['companion'], ':user_2'=>Yii::app()->user->id)
			));
			
			$this->renderPartial('_messagesList', array(
				'messages'  => $messages
			));	
		}else{
			$this->redirect(Yii::app()->createUrl('profile/index', array('id'=>Yii::app()->user->id)));
		}
	}	
	
	public function actionCreateMessage(){
		
				
			$this->render('createMessage');
	
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Messages::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}
